import crypto from 'crypto';
import axios from "axios";

const customer_id = "59419162";
const secretKey = "622A81F5D694476BBFD0684D517FE1BD";
const http_url_api = "https://open-dev.yesmro.cn/api/";
const token_url = "http://localhost:4350/Ym/GetYmToken";


// 修正后的 makeRequest 函数
export async function makeRequest(url, jsonData, method = "get") {
  const timeSpan = (BigInt(Date.now()) * 10000n + 621355968000000000n).toString();
  try {
    const data = jsonData ?? {};
    //console.log(data);
    const token = await getYimToken(data,timeSpan);
    const headers = getHeaders(token,timeSpan);
    const fullUrl = `${http_url_api}${url}`;
    //console.log(data, method, fullUrl, headers);
    const response = await axios({
      method: method.toLowerCase(),
      url: fullUrl,
      data,
      headers,
    });
    //console.log("Response data:", response.data);
    return response.data;
  } catch (error) {
    console.error("Request error:", {
      message: error.message,
      responseData: error.response?.data,
      status: error.response?.status,
      config: error.config,
    });
    return error.response?.data || { error: "Request failed" };
  }
}

// 修正后的 getYmToken 函数
export async function getYimToken(jsonStr,timeSpan) {
  try {
    const response = await axios.post(`${token_url}`+"?secretKey=" + secretKey+"&timeSpan="+timeSpan, { jsonStr });
    return response.data.token;  // 确保返回 response.data
  } catch (error) {
    console.error("请求出错:", error);
    throw error;  // 抛出错误，以便外部可以捕获
  }
}

// 生成请求头
export function getHeaders(token,timeSpan) {
  return {
    "content-type": "application/json;charset=utf-8",
    "x-yesmro-sign": token,
    TimeSpan: timeSpan,
    customerId: customer_id,
    Accept: "*/*",
    Host: "open-dev.yesmro.cn",
    Connection: "keep-alive",
  }
}


